import { lazyReportBatch } from "../report";

export const originProto = XMLHttpRequest.prototype;
export const originalSend = originProto.send;
export const originalOpen = originProto.open;

function overwriteOpenAndSend(){
    originProto.open = function newOpen(...args){
        this.url = args[1];
        this.method = args[0];
        originalOpen.apply(this, args);
    }

    originProto.send = function newSend(...args) {
        this.startTime = Date.now();
        const onLoaded = () => {
            this.endTime = Date.now();
            this.duration = this.endTime - this.startTime;
            const {url,method,startTime,endTime,duration,status} = this
            const reportData = {
                url,
                method:method.toUpperCase(),
                startTime,
                endTime,
                duration,
                status,
                type:'performance',
                success:status >= 200 && status < 300,
                subType:'xhr'
            }
            // 发送数据
            lazyReportBatch(reportData);
            this.removeEventListener('loadend', onLoaded,true);
        }
        this.addEventListener('loadend', onLoaded,true);
        originalSend.apply(this, args);
    }
}

export default function xhr(){
    overwriteOpenAndSend();
}